<template>
  <div class="addproductPage">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <div class="basic-info">基本信息</div>

      <el-form-item label="产品分类" prop="categoryId">
        <el-select
          @change="selectOrigin2"
          size="small"
          clearable
          v-model="ruleForm.categoryId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in List2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="产品类型" prop="type">
        <el-radio-group v-model="ruleForm.type" @change="select1">
          <el-radio :label="0">虚拟</el-radio>
          <el-radio :label="1">实物</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="产品编码" prop="goodId" required>
        <el-input
          v-model="ruleForm.goodId"
          placeholder="请填写SPU编码，来自于泰康之家/泰康拜博"
        ></el-input>
      </el-form-item>
      <el-form-item label="产品名称" prop="goodName" required>
        <el-input
          style="width:500px;"
          v-model="ruleForm.goodName"
          placeholder="请填写名称,不超过30个字"
          maxlength="30"
        ></el-input>
      </el-form-item>
      <el-form-item label="产品来源" prop="channel" required>
        <el-select
          v-model="ruleForm.channel"
          placeholder="请选择(拜博/健投)"
          @change="selectOrigin"
        >
          <el-option
            v-for="item in placeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
          <!-- <el-option label="建投" value="建投"></el-option>
          <el-option label="拜博" value="拜博"></el-option> -->
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="商品图片">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/v1/addimg/food'"
          :show-file-list="false"
          :on-success="uploadImg"
          :before-upload="beforeImgUpload"
        >
          <img
            v-if="foodForm.image_path"
            :src="baseImgPath + foodForm.image_path"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item> -->

      <el-row>
        <el-col :span="10">
          <el-form-item label="图片" prop="pic" required>
            <el-upload
              class="upload-demo"
              ref="upd"
              accept="image/png,image/jpeg"
              :action="setUrl"
              :headers="headers"
              :on-success="successUp"
              :on-error="errorUp"
              :before-upload="beforeUpd"
            >
              <el-button type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，长度比为1:1,且不超过500k
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col style="text-align:center" :span="14"> </el-col>
        <img :src="ruleForm.pic" alt style="width:60px;height:60px;" />
      </el-row>

      <div class="basic-info" style="margin-bottom: 20px">产品信息</div>

      <el-form-item
        label="产品描述"
        prop="description"
        style="margin-top: 20px"
      >
        <el-input
          v-model="ruleForm.description"
          placeholder="字数不超过20"
          maxlength="20"
        ></el-input>
      </el-form-item>
      <el-form-item label="现价" prop="marketPrice">
        <el-input-number
          v-model="ruleForm.marketPrice"
          :min="0"
          :controls="false"
          :precision="2"
          required
          placeholder="小数点后保留2位"
        ></el-input-number
        ><span class="abs">元</span>
      </el-form-item>
      <el-form-item label="划线价" prop="originalPrice" type="number">
        <el-input-number
          v-model="ruleForm.originalPrice"
          :min="0"
          placeholder="要求大于现价"
          type="number"
          :controls="false"
          :precision="2"
        ></el-input-number
        ><span class="abs">元</span>
      </el-form-item>
      <el-form-item label="产品链接" prop="url" required>
        <el-input
          v-model="ruleForm.url"
          placeholder="产品详情url地址"
        ></el-input>
      </el-form-item>

      <div class="More-settings">更多设置</div>

      <el-form-item label="产品排序" prop="showOrder">
        <el-input
          v-model="ruleForm.showOrder"
          style="width: 400px"
          placeholder="整数，数字越小排序越靠前，相同数字，按照上架时间倒序"
        ></el-input>
      </el-form-item>

      <el-form-item label="上架设置" prop="goodStatus">
        <el-radio-group @change="select" v-model="radio">
          <el-radio :label="0">立即上架</el-radio>
          <el-radio :label="2">定时上架 </el-radio>
          <el-date-picker
            style="width: 250px"
            v-model="ruleForm.showShelfTime"
            @change="timechange1"
            format="yyyy-M-dd HH:mm:ss"
            type="datetime"
            placeholder="选择上架时间"
          >
          </el-date-picker>
          <el-radio :label="1" style="margin-left: 30px">暂不上架</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="下架设置" prop="goodStatus">
        <el-radio-group>
          <el-checkbox
            label="定时下架"
            style="margin-right: 20px"
          ></el-checkbox>
          <el-date-picker
            @change="timechange2"
            v-model="ruleForm.offShelfTime"
            type="datetime"
            format="yyyy-M-dd HH:mm:ss"
            placeholder="选择下架时间"
          >
          </el-date-picker>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="活动标签" prop="label">
        <el-select
          @change="selectOrigin1"
          size="small"
          clearable
          
          v-model="ruleForm.label"
          placeholder="请选择"
        >
          <el-option
            v-for="item in List"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

     
      <el-form-item label="产品标签">
        <el-tag
          :key="index"
          v-for="(tag,index) in dynamicTags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-autocomplete
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          :popper-append-to-body="false"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          @select="handleSelect"
          @keyup.enter.native="handleInputConfirm"
          @input="change"
        >
        </el-autocomplete>
        <el-button v-else class="button-new-tag" size="small" @click="showInput"
          >+ 新标签</el-button
        >
      </el-form-item>

      <el-form-item label="是否推广" prop="promotion">
        <el-radio-group v-model="ruleForm.promotion" @change="select2">
          <el-radio :label="0">是</el-radio>
          <el-radio :label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import goodsApi from "@/api/lejv/goods";
import setting from "@/settings"
import {getToken} from "@/utils/auth"
import {
  getGoodsList
} from "@/api/lejv/goods";
export default {
  data() {
    var validatemarketPrice = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请填写现价"));
      } else {
        // if (value >= this.ruleForm.originalPrice){

        //   callback(new Error('划线价低于原价，请重新输入'));
        // }
        callback();
      }
    };
    var validateoriginalPrice = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        if (value <= this.ruleForm.marketPrice) {
          callback(new Error("划线价低于原价，请重新输入"));
        }
        callback();
      }
    };
    var checkUrl = (rule, value, callback) => {
      //自定义校验规则,验证网址是否输入正确
      //       if (this.ruleForm.url !== "") {
      //         let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
      //         if (!reg.test(this.ruleForm.url)) {
      //           callback(new Error("请输入正确的网址!"));
      //         } else {
      //           callback();
      //         }
      //       } else {
      //         callback();
      //       }
      if (this.ruleForm.url !== "") {
        let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])/;
        if (!reg.test(this.ruleForm.url)) {
          return callback(new Error("请填写http,https开头的产品链接"));
        }
        callback();
      } else {
        return callback(new Error("请填写产品链接"));
      }
    };
    return {
      baseUrl: "",
      setUrl:"",
      radio: "",
      img: "",
      flag: 0,
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      restaurants: [],
      headers: { Authorization: getToken() },
      ruleForm: {
        type: "",
        code: "", //编码
        goodName: "",
        goodId: "",
        channel: "",
        description: "",
        originalPrice: "",
        marketPrice: "",
        url: "",
        goodStatus: "",
        pic: "",
        showShelfTime: "",
        offShelfTime: "",
        labelId: "",
        labelcard: "",
        categoryId:'',
        promotion:0,
        labelType: "0",
        label:"",
        
        shelfLabelDataList:[]
      },
      rules: {
        goodId: [
          {
            required: true,
            message: "请填写SPU编码",
            trigger: "blur",
          },
        ],
        categoryId:[
          { required: true, message: "请选择产品分类", trigger: "change" },
        ],
        channel: [
          { required: true, message: "请选择健投或拜博", trigger: "blur" },
        ],
        pic: [{ required: true, message: "请上传产品主图", trigger: "blur" }],
        marketPrice: [
          // { required: true, message: "请保留小数点后2位", trigger: "blur" },
          { validator: validatemarketPrice, required: true, trigger: "blur" },
        ],
        originalPrice: [
          // { message: "划线价低于原价,请重新输入", trigger: "blur" },
          { validator: validateoriginalPrice, trigger: "blur" },
        ],
        goodName: [
          {
            required: true,
            min: 2,
            max: 60,
            message: "请填写产品名称",
            trigger: "blur",
          },
        ],
        url: [{ required: true, validator: checkUrl, trigger: "blur" }],
      },
      timeout:"",
      foodForm: {
        image_path: "",
      },
      placeList: [
        {
          value: "B",
          label: "拜博",
        },
        {
          value: "A",
          label: "健投",
        },
      ],
      List: [
        // { id: 1 ,label: "新品" },
        // { id: 2, label: "促销" },
        // { id: 3, label: "特价" },
        // { id: 4, label: "限时" },
        // { id: 5, label: "秒杀" },
      ],
       List2: [
        // { id: 0,
        //  label: "养康" ,

        // },
        // { id: 1,
        //   label: "齿科"
        // },
        // { id: 2,
        //   label: "体检" ,
        //   disabled: true
        // },
        // { id: 3,
        //   label: "保险",
        //   disabled: true
        // },
        // { id: 4 ,
        //   label: "其他",
        //   disabled: true
        // },
      ],
      isDetail: true,
      id: "",
      isUpd: false, //隐藏图片
    };
  },
  created() {
    // this.setUrl = setting.host + "/file/image/auth"
    // this.setUrl = "https://tklifeac.mobile.taikang.com/file/image/auth"  //生产环境需改为https
    this.setUrl = window.location.host.indexOf('tk') != -1 ? (window.location.protocol + "//" + window.location.host + "/file/image/auth") : "http://tklifeacuat.mobile.taikang.com/file/image/auth"
    // console.log('------this.setUrl', this.setUrl)
    this.getlabel()
    this.getcategories()
  },
  filters: {
    channelFilter(channel) {
      if (channel == "A") return "健投";
      if (channel == "B") return "拜博";
    },
  },
  mounted(){
    // this.restaurants = this.loadAll();
    // this.getcategories()
  },
  methods: {
    //产品标签接口
    getlabel(){

      goodsApi.getlabel(0).then(res=>{
        console.log(res.data)
        if(res.code == 0){
            console.log(res.data)
           this.List=res.data.map(item=>({
             value:item.id,
             label:item.labelName
           }))
          console.log(this.List)
        }
      }

      )

    },
    // 产品分类接口
    getcategories(){

      goodsApi.getcategories().then(res=>{
        console.log(res)
        if(res.code== 0){
           console.log(res.data)
           this.List2=res.data.map(item=>({
             value:item.id,
             label:item.categoryName
           }))
            console.log(this.List2)
            }
        }
          )
    },
    //推荐标签模糊查询
    getquery(name){
      let obj={
        labelType:"1",
        labelName: name
      }
      console.log(this.inputValue)
      if(this.inputValue){
        goodsApi.getquery(obj).then(res=>{
        if(res.data){
          this.restaurants=res.data.map(item=>({
            value:item.labelName,
            id:item.id
          }))
          // this.$refs.saveTagInput.blur()
          let ipt = document.querySelectorAll(".el-input__inner")[12]
          ipt.blur()
          console.log(ipt)
          this.$refs.saveTagInput.focus()
        }

        console.log(res,this.restaurants)
     })
      }
      
    },
    change(){
      if(this.timeout) {
        clearTimeout(this.timeout)
      }
      // wait = 800 为设定的时间, 可以根据需求指定
      this.timeout = setTimeout(() => {
        // 调用接口 处理逻辑
        this.getquery(this.inputValue)
      },800)

    },
    select1(val) {
      this.ruleForm.type = val;
      console.log(val);
    },
    select(val) {
      // this.flag = val
      this.ruleForm.goodStatus = val;
      console.log(val);
    },
    select2(val) {
      this.ruleForm.promotion = val;
      console.log(val);
    },
    timechange1: function (val) {
      console.log(val);
      this.ruleForm.showShelfTime = val;
      console.log(this.ruleForm.showShelfTime);
    },
    timechange2: function (val) {
      console.log(val);
      this.ruleForm.offShelfTime = val;
      console.log(this.ruleForm.offShelfTime);
    },
    //选择来源
    selectOrigin(val) {
      console.log(val);
      this.ruleForm.channel = val;
    },
    selectOrigin1(val) {
      this.ruleForm.shelfLabelDataList = this.ruleForm.shelfLabelDataList.filter(item=>item.labelType!="0")
      let index=this.List.findIndex(item=>
      item.value==val
      )
      // if(index){
        this.ruleForm.label =this.List[index].label;
      // }else{
      //   this.ruleForm.label=""
      // }
      console.log(val,this.List,index);
      let obj ={
        labelType:"0",
        labelName:this.List[index].label,
        id:val
      }
      this.ruleForm.shelfLabelDataList.push(obj)
      console.log(obj);
    },
    // empty(val){
    //   console.log(this.ruleForm.label)
    // },
    selectOrigin2(val) {
      this.ruleForm.categoryId = val;
      console.log(val);
    },
    handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        console.log(111)
      },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
     handleInputConfirm() {
        // let inputValue = this.inputValue;
        let obj=null
        if (this.inputValue) {
          this.dynamicTags.push(this.inputValue);
          obj={
            labelName:this.inputValue,
            labelType:"1"
          };
          if(this.ruleForm.labelId){
            obj.id = this.ruleForm.labelId
            this.ruleForm.labelId=""
          }
          this.ruleForm.shelfLabelDataList.push(obj)
          // this.ruleForm.shelfLabelDataList = this.ruleForm.shelfLabelDataList.filter(item => 
          //  item.labelName != this.dynamicTags.find(val => val == item.labelName))
        }
        this.inputVisible = false;
        this.inputValue = '';
        console.log(this.dynamicTags,this.ruleForm.shelfLabelDataList)

          this.getquery(this.dynamicTags[this.dynamicTags.length-1])


      },
     querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
       handleSelect(event) {
        console.log(event,this.ruleForm.shelfLabelDataList);
        this.ruleForm.labelId = event.id
        this.handleInputConfirm()
      },
      //  loadAll() {
      //   return [
      //     { "value": "三全鲜食（北新泾店）", "address": "长宁区新渔路144号" },
      //     { "value": "胖仙女纸杯蛋糕（上海凌空店）", "address": "上海市长宁区金钟路968号1幢18号楼一层商铺18-101" },
      //     { "value": "高客", "address": "上海市长宁区金钟路633号" },
      //     { "value": "豪大大香鸡排超级奶爸", "address": "上海市嘉定区曹安公路曹安路1685号" },
      //     { "value": "茶芝兰（奶茶，手抓饼）", "address": "上海市普陀区同普路1435号" },
      //     { "value": "娃哈哈", "address": "上海市北翟路1444弄81号B幢-107" },
      //   ];
      // },

    //上传图片
    successUp(val) {
      // this.ruleForm.picUrl = val.slice(49);
      this.img = val;
      this.ruleForm.pic = val; //图片转换
      console.log(this.ruleForm.pic);
      this.$refs.upd.clearFiles();
      // this.isUpd = false;
      this.$message({
        type: "success",
        message: "上传成功!",
      });
  },
  //上传失败
    errorUp(val){
      this.$message({
        type: "error",
        message: "上传失败!",
      });
    },
    //上传图片验证
    beforeUpd(file) {
      // console.log(file);
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const fileType =
        testmsg.toLowerCase() === "jpg" ||
        testmsg.toLowerCase() === "jpeg" ||
        testmsg.toLowerCase() === "png";
      const fileLimit = file.size / 1024 < 500;
      if (!fileType) {
        this.$message({
          message: "上传图片只能是jpg / png 格式!",
          type: "error",
        });
        return false; //必须加上return false; 才能阻止
      }
      if (!fileLimit) {
        this.$message({
          message: "上传文件大小不能超过 500k!",
          type: "error",
        });
        return false;
      }
      return fileLimit || fileType;
    },
    cancel() {
      this.$router.push("/goods/kind");
    },
    resetForm(formName) {
      this.$router.push("/goods/kind");
    },
    submitForm(formName) {
      let params = {
        goodId: this.ruleForm.goodId,
        channel: this.ruleForm.channel,
        goodName: this.ruleForm.goodName,
        originalPrice: this.ruleForm.originalPrice
          ? this.ruleForm.originalPrice
          : "",
        marketPrice: this.ruleForm.marketPrice,
        pic: this.ruleForm.pic,
        url: this.ruleForm.url,
        type: this.ruleForm.type,
        description: this.ruleForm.description,
        goodStatus: this.ruleForm.goodStatus,
        showOrder: this.ruleForm.showOrder,
        showShelfTime: this.ruleForm.showShelfTime,
        offShelfTime: this.ruleForm.offShelfTime,
        label: this.ruleForm.label,
        categoryId:this.ruleForm.categoryId,
        promotion:this.ruleForm.promotion,
        shelfLabelDataList:this.ruleForm.shelfLabelDataList

      };
      this.$refs[formName].validate((valid) => {
        console.log(valid);
        if (valid) {
          console.log(params);
          goodsApi.getGoodsList(params).then((res) => {
            if (res.code == 0) {
              this.$router.push("/goods/kind");
            } else if (res.code == 11202) {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        } else {
          alert("请填写全信息再提交");
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
.addproductPage {
  padding-left: 20px;
}
.product-mode {
  padding-top: 15px;
  padding-bottom: 15px;
  margin-bottom: 30px;
  border-bottom: 1px solid lightgrey;
  span {
    height: 10px;
    padding-top: 150px;
  }
}
.basic-info {
  background: rgb(228, 228, 228);
  padding-left: 30px;
  padding-top: 20px;
  padding-right: 30px;
  padding-bottom: 10px;
  margin-bottom:  10px;
}
.product-type {
  margin-top: 20px;
  display: flex;
  .el-button {
    background: white;
    color: black;
    margin-right: 40px;
  }
}
.el-input {
  width: 300px;
}
.More-settings {
  background: rgb(228, 228, 228);
  padding-left: 30px;
  padding-top: 10px;
  padding-right: 30px;
  padding-bottom: 10px;
  margin-bottom: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: 1px solid black;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
.block {
  margin-left: 100px;
}
.bb {
  display: flex;
}
.fuhzu {
  position: relative !important;
  bottom: 30px;
  left: 100px;
}
.abs {
  margin-left: 30px;
}
.img {
  width: 60px !important;
  height: 60px !important;
  border: 1px solid black;
  position: absolute;
}

.el-tag {
  margin-left: 10px;
  border: 1px solid lightgrey;
  color: black;
  background-color: white;
  line-height: 30px;
  height: 32px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 140px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
